package com.lzf.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzf.domain.dto.ErrorCode;
import com.lzf.domain.dto.ReturnValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 异常处理器
 */
@Component
public class MyExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {
    @Autowired
    private ObjectMapper mapper;

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        headers.set("Content-Type", "application/json;charset=UTF-8");
        ReturnValue returnValue = null;
        if(e instanceof InternalAuthenticationServiceException) {
            returnValue = new ReturnValue<String>(ErrorCode.ERROR_USER_PASSWORD);
        }else if(e instanceof InvalidTokenException) {
            //headers.set("WWW-Authenticate", String.format("%s %s", "Bearer", e));
            returnValue = new ReturnValue<String>(ErrorCode.ERROR_USER_TOKEN_ERROR);
        }else if(e instanceof UnsupportedGrantTypeException){
            returnValue = new ReturnValue<String>(ErrorCode.ERROR_USER_GRANT_TYPE_ERROR);
        }else if(e instanceof InvalidGrantException){
            if(e.getLocalizedMessage().equals("Bad credentials")) {
                //密码错误
                returnValue = new ReturnValue<String>(ErrorCode.ERROR_USER_PASSWORD);
            }else if(e.getLocalizedMessage().contains("Invalid refresh token")){
                //刷新验证码错误
                returnValue = new ReturnValue<String>(ErrorCode.ERROR_USER_REFRENSH_TOKEN_ERROR);
            }
        }else {
            returnValue = new ReturnValue<String>(ErrorCode.ERROR_USER_PASSWORD);
        }
        return new ResponseEntity(mapper.writeValueAsString(returnValue), headers, HttpStatus.OK);
    }
}
